package com.hzqdn.monsterpost.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzqdn.monstermodel.entity.post.PostViews;
import com.hzqdn.monsterpost.mapper.PostViewsMapper;
import com.hzqdn.monsterpost.service.PostViewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class PostViewsServiceImpl extends ServiceImpl<PostViewsMapper, PostViews> implements PostViewsService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    // Redis中帖子浏览量的key前缀
    private static final String POST_VIEW_COUNT_KEY_PREFIX = "post:view:count:";

    @Override
    public boolean addPostViews(Long postId) {
        // 2. 构建Redis key
        String redisKey = POST_VIEW_COUNT_KEY_PREFIX + postId;

        // 3. 增加浏览量
        redisTemplate.opsForValue().increment(redisKey, 1);

        // 4. 设置过期时间（可选，这里设置7天）
        redisTemplate.expire(redisKey, 7, TimeUnit.DAYS);
        return true;
    }

    @Override
    public long getPostViews(Long postId) {
        // 1. 构建Redis key
        String redisKey = POST_VIEW_COUNT_KEY_PREFIX + postId;

        // 2. 从Redis获取浏览量
        Object viewCountObj = redisTemplate.opsForValue().get(redisKey);
        long redisViewCount = 0;
        if (viewCountObj != null) {
            redisViewCount = Long.parseLong(viewCountObj.toString());
        }

        // 3. 如果Redis中没有，则从数据库获取
        if (redisViewCount == 0) {

            // 从数据库获取浏览量
            PostViews views = this.getById(postId);
            if (views != null && views.getViewCount() != null) {
                redisViewCount = views.getViewCount();
                // 将数据库中的浏览量同步到Redis
                redisTemplate.opsForValue().set(redisKey, redisViewCount, 7, TimeUnit.DAYS);
            }
        }

        return redisViewCount;
    }
}
